package com.xo.xodemo.controller;

import CCBSign.RSASig;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.xo.xodemo.common.Result;
import com.xo.xodemo.common.config.QrConfig;
import com.xo.xodemo.mapper.db1.*;
import com.xo.xodemo.mapper.db2.AdminUserMapper;
import com.xo.xodemo.mapper.db2.OrderMapper;
import com.xo.xodemo.model.*;
import com.xo.xodemo.service.CustomerService;
import com.xo.xodemo.service.JHService;
import com.xo.xodemo.springsecurityconfig.CustomUserDetails;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("/")
public class IndexController {
@Autowired
private MenuMapper menuMapper;
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Autowired
private PositionMapper positionMapper;
@Autowired
private AdminUserMapper adminUserMapper;
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
private OrderMapper orderMapper;
@Autowired
private CustomerService customerService;



    @RequestMapping ("login")
    public String login() {
        return "login";
    }
    @RequestMapping("main")
    public String main(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //经过认证的用户
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            String currentUserName = authentication.getName();
            Integer positionId=userMapper.selectPositionByName(currentUserName);
            List<Menu> menus=menuMapper.findParentMenu(positionId);
            for(Menu m:menus){
                m.setSecondMenus(menuMapper.findChildMenu(m.getMenuId(),positionId));
            }
            model.addAttribute("menus",menus);
            model.addAttribute("userName",userDetails.getRealName());
            String positionName=positionMapper.findPositionNameByPositionId(positionId);
            model.addAttribute("positionName",positionName);
            model.addAttribute("realName",userDetails.getRealName());
            return "main";
        }
        else {
            return  "login";
        }
    }
    //用户详情(自己改自己的)
    @RequestMapping("/revise")
    public String revise( Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        //经过认证的用户
        if (!(authentication instanceof AnonymousAuthenticationToken)) {
            String currentUserName = authentication.getName();
            List<ReturnUser> d=userMapper.selectReviseData(currentUserName);
            ReturnUser user=d.get(0);
            model.addAttribute("user",user);
            return   "system/userRevise";
        }
        return   "system/userRevise";

    }
    @RequestMapping("processadd")
    public String process(Model model) {

        return  "process/processadd";

    }
    //我的流程
    @RequestMapping ("/myprocess")
    public String myprocess() {


        return  "process/myprocess";
    }
    //我的审核
    @RequestMapping ("/processauditing")
    public String processauditing() {


        return  "process/processauditing";
    }
    //资源管理新增界面
    @RequestMapping ("/resourceadpage")
    public String resourceaddpage() {


        return  "resource/resourceaddpage";
    }
    //资源管理查询界面
    @RequestMapping ("/resourcequerypage")
    public String resourcequerypage() {


        return  "resource/resourcequerypage";
    }
    //快手查询界面
    @RequestMapping ("/ksdatareceptionpage")
    public String ksdatareceptionoutsidepage() {


        return  "ksdatareception/ksdatareceptionpage";
    }
    //抖音查询界面
    @RequestMapping ("/dydatareceptionpage")
    public String dydatareceptionoutsidepage() {


        return  "dydatareception/dydatareceptionpage";
    }
    //快手查询界面外界
    @RequestMapping ("/ksdatareceptionoutsidepage")
    public String ksdatareceptionpage() {


        return  "ksdatareception/ksdatareceptionoutsidepage";
    }
    //抖音查询界面外界
    @RequestMapping ("/dydatareceptionoutsidepage")
    public String dydatareceptionpage() {


        return  "dydatareception/dydatareceptionoutsidepage";
    }
    //系统权限管理页面
    @RequestMapping ("/positionshow")
    public String ositionshow(Model model) {
        List<Role> lp=roleMapper.findAll();
        model.addAttribute("rolelist",lp);
        return  "system/positionShow";
    }
    //用户管理页面
    @RequestMapping ("/usershow")
    public String usershow(Model model) {
        return  "system/userShow";
    }
    //用户管理页面
    @RequestMapping ("/salesstatistics")
    public String salesstatistics(Model model) {
        return  "salesstatistics/salesstatistics";
    }
    //部门管理页面
    @RequestMapping ("/departmentshow")
    public String departmentshow(Model model) {
        return  "system/departmentShow";
    }
    //商品展示页面
    @RequestMapping ("/goodsshow")
    public String qrcode(@RequestParam("userId") String userId,@RequestParam("buyType") String buyType,@RequestParam("userType") String userType,Model model) {
        model.addAttribute("userId",userId);
        model.addAttribute("userType",userType);
        model.addAttribute("buyType",buyType);
        return  "goods/goodspage";
    }
    //推送管理（365推送）
    @RequestMapping ("/pushinfo")
    public String pushshow(Model model,@AuthenticationPrincipal CustomUserDetails userDetails) {
        model.addAttribute("userDetails",userDetails);
        return  "pushinfo/pushinfo";
    }
    //推送管理（365推送）
    @RequestMapping ("/mypushinfo")
    public String mypushshow(Model model) {
        return  "pushinfo/mypushinfo";
    }
    // 新增
    @RequestMapping ("/salesstatisticss")
    public String salesstatisticss() {
        return  "sale/salesstatisticss";
    }
    //付款回调接口
    @PostMapping ("/goodsreturn")
    @ResponseBody
    public String goodsreturn(PayCallBackEntity pa, @RequestBody String str) throws IOException, ParseException {
        if(!"Y".equals(pa.getSUCCESS())||pa.getACCDATE()==null||"".equals(pa.getACCDATE())){
            System.out.println("未成功");
            return  "未成功";
        }
        //如果效验不成功
        if(!paycallverify(str)){
            System.out.println("加密效验失败");
            return  "加密效验失败";
        }
        String userId=pa.getREMARK1();
        String buyType=pa.getREMARK2();
        String rs=stringRedisTemplate.boundValueOps(pa.getORDERID()).get();
        if(rs==null){
                System.out.println("缓存效验失败");
                return  "加密效验失败";
        }
        Order order= JSON.parseObject(rs,Order.class);
        if(Double.parseDouble(order.getPayment())!=Double.parseDouble(pa.getPAYMENT())){
            System.out.println("金额效验失败");
            return  "金额效验失败";
        }
        //以下数字为订单设置的编号
        if("1".equals(buyType)||"2".equals(buyType)){
            customerService.renewaloneyear(userId);
        }

        if("3".equals(buyType)){
            customerService.bzbpurchase(userId);
        }
        if("4".equals(buyType)){
            customerService.jdbpurchase(userId);
        }
        if("5".equals(buyType)){
             customerService.zxbpurchase(userId);
        }
        order.setSuccess("Y");
        order.setVerify("Y");
        order.setAcceptType(pa.getACC_TYPE());
        order.setTime(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
        //更新订单状态
        orderMapper.initnew(order);

      return  "支付成功";
    }
    private boolean  paycallverify(String str){
        //签名校验
        String[] split = str.split("&SIGN=");
        String src = split[0];
        String sign = split[1];
        RSASig rsaSig = new RSASig();
        rsaSig.setPublicKey(QrConfig.PUB);
        boolean b = rsaSig.verifySigature(sign, src);

        return b;
    }

}
